<template>
  <el-form ref="ruleFormRef" style="max-width: 600px" :model="ruleForm" :rules="rules" label-width="auto"
    class="demo-ruleForm" :size="formSize" status-icon>

    <el-form-item label="手机号" prop="username">
      <el-input v-model="ruleForm.username" placeholder="请输入手机号" />
    </el-form-item>

    <el-form-item label="密码" prop="password">
      <el-input v-model="ruleForm.password" type="password" placeholder="请输入密码" />
    </el-form-item>

    <el-form-item>
      <el-button type="primary" @click="submitForm(ruleFormRef)">
        登录
      </el-button>
      <el-button @click="resetForm(ruleFormRef)">重置</el-button>
    </el-form-item>
  </el-form>
</template>

<script setup lang='ts'>
import { reactive, ref } from "vue";
import { useRouter } from 'vue-router'
// 假设这是你的登录API
// import { loginApi } from '@/api/auth'

const formSize = ref("default");
const ruleFormRef = ref();
const router = useRouter()

const ruleForm = reactive({
  username: "",  // 手机号
  password: "",   // 密码
});

// 手机号验证器
const validatePhone = (rule, value, callback) => {
  if (!value) {
    callback(new Error('请输入手机号'))
  } else if (!/^1[3-9]\d{9}$/.test(value)) {
    callback(new Error('请输入正确的手机号格式'))
  } else {
    callback()
  }
}

// 密码验证器
const validatePassword = (rule, value, callback) => {
  if (!value) {
    callback(new Error('请输入密码'))
  } else if (value.length < 8) {
    callback(new Error('密码长度不能少于8位'))
  } else {
    callback()
  }
}

const rules = reactive({
  username: [
    { validator: validatePhone, trigger: "blur" },
  ],
  password: [
    { validator: validatePassword, trigger: "blur" },
  ],
});
const submitForm = async (formEl) => {
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
    const res = { data: 'mock-token' }
    localStorage.setItem("token", res.data)
    // 跳转到首页或之前的页面
    router.push('/about')

      console.log("submit!");
    } else {
      console.log("error submit!", fields);
    }
  });
};

const resetForm = (formEl) => {
  if (!formEl) return;
  formEl.resetFields();
};
</script>

<style lang="scss" scoped>
.el-form {
  margin: 0 auto;
  position: fixed;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  border: 1px solid #e5e7eb;
  padding: 30px;
  border-radius: 10px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
  background-color: #fff;

  .el-form-item {
    margin-bottom: 20px;
  }
  
  .el-button + .el-button {
    margin-left: 10px;
  }
}
</style>
